#include "PS_Log.h"
#include <sstream>

Postscript_Stream *PS_Log::ps;

void PS_Log::open(const std::string& filename) {
    ps = new Postscript_Stream(filename);
}

void PS_Log::close() {
    ps->close();
}

void PS_Log::print_fnf(fnf_graph_t& fnf) {
    LOG_ENTER(SPLIT, "print_fnf");

    fnf_vertex_range_t v_iters = fnf.get_vertices();
    fnf_vertex_iter_t v_iter = v_iters.first;
    fnf_vertex_iter_t v_end  = v_iters.second;
    for (; v_iter != v_end; v_iter++) {
        FNF_Vertex_Info vp = fnf.properties(*v_iter);
        PS_Log::ps->draw_dot(vp.x, vp.y, vp.color == 0);
        std::stringstream label;
//        label << '(' << vp.x << ' ' << vp.y << ')';
        label << fnf.get_vertex_name(*v_iter);
        PS_Log::ps->label_dot(label.str(), vp.x, vp.y);
    }

    fnf_edge_range_t e_iters = fnf.get_edges();
    fnf_edge_iter_t e_iter = e_iters.first;
    fnf_edge_iter_t e_end  = e_iters.second;
    for (; e_iter != e_end; e_iter++) {
        fnf_vertex_t src = fnf.get_source(*e_iter);
        fnf_vertex_t dst = fnf.get_target(*e_iter);
        FNF_Vertex_Info src_vp = fnf.properties(src);
        FNF_Vertex_Info dst_vp = fnf.properties(dst);
        PS_Log::ps->join_dots(src_vp.x, src_vp.y,
                              dst_vp.x, dst_vp.y);
    }

    PS_Log::ps->end_page();
    PS_Log::ps->flush();

    LOG_EXIT();
}

void PS_Log::print(Pile& pile, bool solid) {
    LOG_ENTER(SPLIT, "print(pile)");

    Iterator<Item*> *iter = pile.new_iterator();
    for (int i=0; iter->has_next(); i++) {
        Item *p = iter->get_next();
        PS_Log::ps->draw_dot(p->x, p->y, solid);
        std::ostringstream label;
//        label << '(' << p->name << ')';
        label << p->ID;
        PS_Log::ps->label_dot(label.str(), p->x, p->y);
    }
    delete iter;
    PS_Log::ps->flush();

    LOG_EXIT();
}

void PS_Log::print(Item **items, int size,
                   int start, int end, bool solid) {
    LOG_ENTER(SPLIT, "print(item array)");
    LOG(SPLIT) << "size=" << size << " start=" << start << " end=" << end << " solid=" << (solid? "true" : "false");

    for (int i=start; i < size && i <= end; i++) {
        Item *p = items[i];
        PS_Log::ps->draw_dot(p->x, p->y, solid);
        std::ostringstream label;
//        label << '(' << p->name << ')';
        label << p->ID;
        PS_Log::ps->label_dot(label.str(), p->x, p->y);
    }
    PS_Log::ps->flush();

    LOG_EXIT();
}

void PS_Log::show_title(const std::string& title) {
    PS_Log::ps->draw_caption(title);
}
